const matchParams =function(url, args) {
  let re = /{(.*?)}/g
  let params = {}
  let count = 0
  let temp = ''
  while (temp = re.exec(url)) {
    params[temp[1]] = args[count]
    count += 1
  }
  if (count === 0) return false
  return params
}


const setUrl =function(url, args) {
  let params = matchParams(url, args)
  let data = {}
  if (typeof args[0] === 'object') {
    data = args[0]

    for (let key in params) {
      let keys = key.split(':')
      if (keys.length === 2) {
        params[key] = data[keys[1]]
      } else {
        params[key] = data[key]
      }
    }
  }
  // 将参数进行分组 queryString | pathVarible
  const querys = url.split('?')
  let queryStrings = []
  let pathVaribles = []
  if (querys.length > 1) {
    queryStrings = querys[1].split('&')
  }
  let newUrl = querys[0]
  // 分离 pathVarible
  let firstSpeatorIndex = querys[0].indexOf('{')

  if (firstSpeatorIndex !== -1) {
    let pathVarible = querys[0].substring(firstSpeatorIndex)
    newUrl = querys[0].substring(0, firstSpeatorIndex)
    pathVaribles = pathVarible.split('/')
  }

  let newPathVaribles = []
  let newQueryStrings = []

  pathVaribles.forEach((par,index) => {

    newPathVaribles.push(par)
    for (let key in params) {
      if (par === `{${key}}` && params[key] !== undefined && params[key] !== '') {
        // newPathVaribles.push(params[key])
        newPathVaribles[index] = params[key]
        delete data[key]
      }
    }
  })

  queryStrings.forEach(par => {
    for (let key in params) {
      let keys = key.split(':')
      if (par === `{${key}}` && params[key] !== undefined && params[key] !== '') {
        newQueryStrings.push(`${keys[0]}=${params[key]}`)
        delete data[key]
      }
    }
  })


  newUrl = newUrl + newPathVaribles.join('/')

  if (newQueryStrings.length !== 0) {
    newUrl = newUrl + '?' + newQueryStrings.join('&')
  }
  url = newUrl
  return {
    url,
    data
  }
}

module.exports ={setUrl}